from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form
from sqlalchemy.orm import Session
from typing import Optional

from app import models
from app.api import deps
from app.services.storage_manager import storage_manager
from app.services.storage_base import FileType
from app.core.config import settings

router = APIRouter()

@router.post("/upload-avatar")
async def upload_avatar(
    file: UploadFile = File(...),
    db: Session = Depends(deps.get_db),
    current_user: models.User = Depends(deps.get_current_user),
):
    """上传用户头像"""
    
    # 验证文件类型
    if file.content_type not in settings.ALLOWED_IMAGE_TYPES:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型。支持的类型: {', '.join(settings.ALLOWED_IMAGE_TYPES)}"
        )
    
    # 验证文件大小
    file_content = await file.read()
    if len(file_content) > settings.MAX_FILE_SIZE:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大。最大支持 {settings.MAX_FILE_SIZE // 1024 // 1024}MB"
        )
    
    try:
        # 上传到对象存储
        storage_service = storage_manager.get_service()
        if not storage_service:
            raise HTTPException(status_code=500, detail="存储服务不可用")
        
        result = await storage_service.upload_file(
            file_data=file_content,
            file_name=file.filename,
            file_type=FileType.AVATAR,
            content_type=file.content_type
        )
        
        if not result.success:
            raise HTTPException(status_code=500, detail=result.error_message)
        
        # 更新用户头像URL
        current_user.avatar_url = result.file_url
        db.commit()
        
        return {
            "message": "头像上传成功",
            "avatar_url": result.file_url,
            "file_key": result.file_key
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")

@router.post("/upload-image")
async def upload_image(
    file: UploadFile = File(...),
    current_user: models.User = Depends(deps.get_current_user),
):
    """上传图片文件（用于AI处理的源图片）"""
    
    # 验证文件类型
    if file.content_type not in settings.ALLOWED_IMAGE_TYPES:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型。支持的类型: {', '.join(settings.ALLOWED_IMAGE_TYPES)}"
        )
    
    # 验证文件大小
    file_content = await file.read()
    if len(file_content) > settings.MAX_FILE_SIZE:
        raise HTTPException(
            status_code=400,
            detail=f"文件太大。最大支持 {settings.MAX_FILE_SIZE // 1024 // 1024}MB"
        )
    
    try:
        # 上传到对象存储
        storage_service = storage_manager.get_service()
        if not storage_service:
            raise HTTPException(status_code=500, detail="存储服务不可用")
        
        result = await storage_service.upload_file(
            file_data=file_content,
            file_name=file.filename,
            file_type=FileType.TEMP,
            content_type=file.content_type
        )
        
        if not result.success:
            raise HTTPException(status_code=500, detail=result.error_message)
        
        return {
            "message": "图片上传成功",
            "image_url": result.file_url,
            "file_key": result.file_key
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")

@router.delete("/files/{file_key}")
async def delete_file(
    file_key: str,
    current_user: models.User = Depends(deps.get_current_user),
):
    """删除文件"""
    
    try:
        storage_service = storage_manager.get_service()
        if not storage_service:
            raise HTTPException(status_code=500, detail="存储服务不可用")
        
        # 验证文件归属（简单的安全检查）
        if f"user_{current_user.id}" not in file_key and not file_key.startswith("temp/"):
            raise HTTPException(status_code=403, detail="无权限删除此文件")
        
        success = await storage_service.delete_file(file_key)
        
        if success:
            return {"message": "文件删除成功"}
        else:
            raise HTTPException(status_code=500, detail="文件删除失败")
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除失败: {str(e)}")

@router.get("/files")
async def list_user_files(
    current_user: models.User = Depends(deps.get_current_user),
    file_type: Optional[str] = None,
    limit: int = 50
):
    """列出用户文件"""
    
    try:
        storage_service = storage_manager.get_service()
        if not storage_service:
            raise HTTPException(status_code=500, detail="存储服务不可用")
        
        # 根据用户ID构建前缀
        if file_type:
            prefix = f"{file_type}/*/user_{current_user.id}/"
        else:
            prefix = f"*/user_{current_user.id}/"
        
        files = await storage_service.list_files(prefix=prefix, limit=limit)
        
        return {
            "files": files,
            "total": len(files)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取文件列表失败: {str(e)}")